import type { Canceler, InternalAxiosRequestConfig } from 'axios';
import axios from 'axios';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

// 请求拦截
const { CancelToken } = axios;
let cancel: Canceler;

// 取消请求白名单
const WhiteCancelList: string[] = [];

const promiseArr: any = {};

axios.defaults.baseURL = import.meta.env.VITE_APP_BASEURL as string;
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    let url: string = config?.url!;
    // console.log('xxxxxxx', url)
    if (config.url) {
      const isInWhiteCancelList = WhiteCancelList.find(item => {
        return url?.includes(item);
      });
      if (promiseArr[url] && !isInWhiteCancelList) {
        promiseArr[url]('操作取消');
        promiseArr[url] = cancel;
      } else {
        promiseArr[url] = cancel;
      }
    }

    // get参数编码
    if (config.method === 'get' && config.params) {
      url += '?';
      const keys = Object.keys(config.params);
      for (const key of keys) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`;
      }
      url = url.substring(0, url.length - 1);
      config.params = {};
    }
    config.url = url;
    config.headers!['Content-type'] = config?.headers!['Content-type']
      ? config.headers['Content-type']
      : 'application/json';
    try {
      if (!config.headers.Authorization) {
        config.headers.Authorization = localStorage.getItem('token');
      }
    } catch (err) {
      //
    }
    return config;
  },
  err => Promise.reject(err)
);
axios.interceptors.response.use(
  response => {
    if ([0, 200, 9802003].includes(response.data?.code) || response?.data?.successful) {
      return Promise.resolve(response.data);
    }
    message.error(response.data.msg || response.data.message || response.data.resultHint);
    return Promise.reject(response.data);
  },
  err => Promise.reject(err.toString())
);
export default {
  get(param: { url: string; data?: {}; headers?: {} }, option = {}) {
    return axios({
      method: 'get',
      url: param.url,
      params: param.data ? param.data : {},
      ...option,
      headers: param.headers ? param.headers : {},
      cancelToken: new CancelToken((c: Canceler) => {
        cancel = c;
      }),
    });
  },
  post(param: { url: string; data?: {}; headers?: {} }, option = {}) {
    return axios({
      method: 'post',
      url: param.url,
      data: param.data || {},
      ...option,
      headers: param.headers ? param.headers : {},
      cancelToken: new CancelToken((c: Canceler) => {
        cancel = c;
      }),
    });
  },
  put(param: { url: string; data?: {}; headers?: {} }, option = {}) {
    return axios({
      method: 'put',
      url: param.url,
      data: param.data || {},
      ...option,
      headers: param.headers ? param.headers : {},
      cancelToken: new CancelToken((c: Canceler) => {
        cancel = c;
      }),
    });
  },
  delete(param: { url: string; data?: {}; headers?: {} }, option = {}) {
    return axios({
      method: 'delete',
      url: param.url,
      data: param.data || {},
      ...option,
      headers: param.headers ? param.headers : {},
      cancelToken: new CancelToken((c: Canceler) => {
        cancel = c;
      }),
    });
  },
};

export function getResult<T>(data: ResponseObject<T>, showError = false): T | Promise<string> {
  if (data?.code === 0) {
    return <T>data.data;
  } else {
    if (showError) {
      message.error(data?.msg);
    }
    return Promise.reject(data?.msg);
  }
}
